package com.dwxt.cdms.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dwxt.cdms.api.common.utils.StringUtil;
import com.dwxt.cdms.util.RedisUtil;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.UUID;


@Service
@Slf4j
public class MinAPPService {


    @Value("${minApp.appid}")
    private  String appid;

    @Value("${minApp.secret}")
    private  String secret;


    public Object getWxacodeunlimit() throws IOException {

    return null;


    }

    public String getAccess_token( ) {
        //从redis中获取
        String accessToken = RedisUtil.get("minAppAccessToken", String.class);
        if (StringUtil.isNotBlank(accessToken)) {
            return accessToken;
        }
        //已过期，重新向微信获取
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid
                +"&secret="+secret;
        String request = HttpUtils.getRequest(url);
        JSONObject jsonObject = JSON.parseObject(request);
        String access_token = (String) jsonObject.get("access_token");
        long expires_in = (Integer) jsonObject.get("expires_in");
        RedisUtil.set("minAppAccessToken", access_token, expires_in - 10);
        return access_token;
    }

    /**
    * @Description: 电视端获取小程序二维码和唯一字符串
    * @Param [request, response]
    * @Return com.dwxt.common.base.BaseResult
    * @Author chendq
    * @Date 2021/12/12
    **/
    public BaseResult getQrCode() throws IOException {
        String access_token = getAccess_token();
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
        HashMap<String, Object> map = new HashMap<>();
        String uuid = UUID.randomUUID().toString().replace("-","");
        map.put("scene", uuid);
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        System.out.println("请求参数：："+ JSON.toJSONString(map));
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
        Request request1 = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cache-Control", "no-cache")
                .build();

        Response response1 = client.newCall(request1).execute();
        ResponseBody body1 = response1.body();
        BufferedSource source = body1.source();
        InputStream inputStream = source.inputStream();
        BufferedImage image = ImageIO.read(inputStream);
        //ImageIO.write(image, "JPEG", response.getOutputStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(image, "png", baos);//写入流中
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        //System.out.println("值为："+"data:image/jpg;base64,"+png_base64);
        map.put("qrCode", "data:image/jpg;base64,"+png_base64);
        map.put("scene", uuid);
        return BaseResult.ok(map);
    }

    public BaseResult allowLogin(String scene, String phone) {
        RedisUtil.set(scene,phone,300l);
        return BaseResult.ok();
    }
}
